    <th:block layout:fragment="scripts">
        <script>
            let opportunities = []; // 存储销售机会数据
            let clients = []; // 存储客户列表
            
            document.addEventListener('DOMContentLoaded', function() {
                loadOpportunities();
                loadClients();
                
                // 设置表单提交事件
                document.getElementById('opportunityForm').addEventListener('submit', function(e) {
                    e.preventDefault();
                    saveOpportunity();
                });
                
                // 设置搜索和筛选事件
                document.getElementById('searchOpportunity').addEventListener('input', filterOpportunities);
                document.getElementById('filterStatus').addEventListener('change', filterOpportunities);
                document.getElementById('filterPriority').addEventListener('change', filterOpportunities);
            });

            // 从服务器加载销售机会列表
            function loadOpportunities() {
                fetch('/api/sales/opportunities/list')
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            opportunities = result.data;
                            renderOpportunities();
                        } else {
                            console.error('加载销售机会列表失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载销售机会列表失败:', error));
            }
            
            // 加载客户列表用于表单选择
            function loadClients() {
                fetch('/api/sales/clients/list')
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            clients = result.data;
                            
                            // 填充客户下拉框
                            const clientSelect = document.getElementById('clientId');
                            clientSelect.innerHTML = '<option value="">请选择客户</option>';
                            
                            clients.forEach(client => {
                                const option = document.createElement('option');
                                option.value = client.id;
                                option.textContent = client.name;
                                clientSelect.appendChild(option);
                            });
                        } else {
                            console.error('加载客户列表失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载客户列表失败:', error));
            }
            
            // 渲染销售机会列表
            function renderOpportunities() {
                const table = document.getElementById('opportunities-table');
                const tbody = table.querySelector('tbody');
                tbody.innerHTML = '';
                
                if (opportunities.length === 0) {
                    const emptyRow = document.createElement('tr');
                    emptyRow.innerHTML = '<td colspan="9" class="text-center">没有找到销售机会数据</td>';
                    tbody.appendChild(emptyRow);
                    return;
                }
                
                opportunities.forEach(opportunity => {
                    const row = document.createElement('tr');
                    
                    // 设置状态样式
                    let statusClass = '';
                    switch(opportunity.status) {
                        case 'NEW': statusClass = 'badge-info'; break;
                        case 'QUALIFIED': statusClass = 'badge-primary'; break;
                        case 'PROPOSITION': statusClass = 'badge-warning'; break;
                        case 'NEGOTIATION': statusClass = 'badge-secondary'; break;
                        case 'WON': statusClass = 'badge-success'; break;
                        case 'LOST': statusClass = 'badge-danger'; break;
                    }
                    
                    // 获取状态对应的显示文本
                    const statusText = {
                        'NEW': '新建',
                        'QUALIFIED': '已确认',
                        'PROPOSITION': '方案阶段',
                        'NEGOTIATION': '谈判阶段',
                        'WON': '已成交',
                        'LOST': '已丢失'
                    }[opportunity.status] || opportunity.status;
                    
                    // 优先级样式
                    let priorityClass = '';
                    switch(opportunity.priority) {
                        case 'LOW': priorityClass = 'text-secondary'; break;
                        case 'MEDIUM': priorityClass = 'text-primary'; break;
                        case 'HIGH': priorityClass = 'text-danger'; break;
                    }
                    
                    // 获取优先级对应的显示文本
                    const priorityText = {
                        'LOW': '低',
                        'MEDIUM': '中',
                        'HIGH': '高'
                    }[opportunity.priority] || opportunity.priority;
                    
                    // 计算预期收入
                    const expectedRevenue = (opportunity.amount * opportunity.probability / 100).toFixed(2);
                    
                    row.innerHTML = `
                        <td>${opportunity.id}</td>
                        <td>${opportunity.name}</td>
                        <td>${opportunity.clientName || '-'}</td>
                        <td>${opportunity.amount.toLocaleString('zh-CN', {style: 'currency', currency: 'CNY'})}</td>
                        <td class="${priorityClass}">${priorityText}</td>
                        <td><span class="badge ${statusClass}">${statusText}</span></td>
                        <td>${opportunity.probability}%</td>
                        <td>${expectedRevenue.toLocaleString('zh-CN', {style: 'currency', currency: 'CNY'})}</td>
                        <td>
                            <button class="btn btn-sm btn-info" onclick="viewOpportunity(${opportunity.id})">查看</button>
                            <button class="btn btn-sm btn-primary" onclick="editOpportunity(${opportunity.id})">编辑</button>
                            <button class="btn btn-sm btn-danger" onclick="deleteOpportunity(${opportunity.id})">删除</button>
                        </td>
                    `;
                    
                    tbody.appendChild(row);
                });
            }

            function showAddOpportunityModal() {
                document.getElementById('modalTitle').textContent = '添加销售机会';
                document.getElementById('opportunityForm').reset();
                
                // 移除可能存在的ID
                document.getElementById('opportunityForm').removeAttribute('data-id');
                
                // 显示模态框
                document.getElementById('opportunityModal').style.display = 'block';
            }

            function closeModal() {
                document.getElementById('opportunityModal').style.display = 'none';
            }

            function editOpportunity(opportunityId) {
                document.getElementById('modalTitle').textContent = '编辑销售机会';
                
                // 获取销售机会详情
                fetch(`/api/sales/opportunities/${opportunityId}`)
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            const opportunity = result.data;
                            
                            // 填充表单
                            document.getElementById('opportunityName').value = opportunity.name;
                            document.getElementById('clientId').value = opportunity.clientId || '';
                            document.getElementById('amount').value = opportunity.amount;
                            document.getElementById('probability').value = opportunity.probability;
                            document.getElementById('priority').value = opportunity.priority;
                            document.getElementById('status').value = opportunity.status;
                            document.getElementById('source').value = opportunity.source || '';
                            document.getElementById('expectedClosingDate').value = opportunity.expectedClosingDate || '';
                            document.getElementById('description').value = opportunity.description || '';
                            
                            // 设置表单ID用于保存
                            document.getElementById('opportunityForm').setAttribute('data-id', opportunity.id);
                            
                            // 显示模态框
                            document.getElementById('opportunityModal').style.display = 'block';
                        } else {
                            console.error('加载销售机会详情失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载销售机会详情失败:', error));
            }
            
            function viewOpportunity(opportunityId) {
                // 跳转到销售机会详情页面
                window.location.href = `/sales/opportunities/${opportunityId}`;
            }
            
            function deleteOpportunity(opportunityId) {
                if (confirm('确定要删除这个销售机会吗？')) {
                    fetch(`/api/sales/opportunities/delete/${opportunityId}`, {
                        method: 'DELETE'
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            // 刷新销售机会列表
                            loadOpportunities();
                        } else {
                            alert('删除销售机会失败: ' + result.message);
                        }
                    })
                    .catch(error => {
                        console.error('删除销售机会失败:', error);
                        alert('系统错误，请稍后重试');
                    });
                }
            }
            
            function saveOpportunity() {
                const form = document.getElementById('opportunityForm');
                const opportunityId = form.getAttribute('data-id');
                const isEdit = !!opportunityId;
                
                // 表单验证
                if (!form.checkValidity()) {
                    form.reportValidity();
                    return;
                }
                
                const opportunityData = {
                    name: document.getElementById('opportunityName').value,
                    clientId: document.getElementById('clientId').value || null,
                    amount: parseFloat(document.getElementById('amount').value),
                    probability: parseInt(document.getElementById('probability').value),
                    priority: document.getElementById('priority').value,
                    status: document.getElementById('status').value,
                    source: document.getElementById('source').value,
                    expectedClosingDate: document.getElementById('expectedClosingDate').value || null,
                    description: document.getElementById('description').value
                };
                
                if (isEdit) {
                    opportunityData.id = parseInt(opportunityId);
                }
                
                const url = isEdit ? '/api/sales/opportunities/update' : '/api/sales/opportunities/add';
                const method = isEdit ? 'PUT' : 'POST';
                
                fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(opportunityData)
                })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        // 关闭模态框，重新加载销售机会列表
                        closeModal();
                        loadOpportunities();
                    } else {
                        alert('保存销售机会失败: ' + result.message);
                    }
                })
                .catch(error => {
                    console.error('保存销售机会失败:', error);
                    alert('系统错误，请稍后重试');
                });
            }
            
            function filterOpportunities() {
                const searchTerm = document.getElementById('searchOpportunity').value.toLowerCase();
                const statusFilter = document.getElementById('filterStatus').value;
                const priorityFilter = document.getElementById('filterPriority').value;
                
                // 构建过滤条件
                const params = new URLSearchParams();
                if (searchTerm) params.append('search', searchTerm);
                if (statusFilter) params.append('status', statusFilter);
                if (priorityFilter) params.append('priority', priorityFilter);
                
                // 发送带参数的请求
                fetch(`/api/sales/opportunities/list?${params.toString()}`)
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            opportunities = result.data;
                            renderOpportunities();
                        } else {
                            console.error('筛选销售机会失败:', result.message);
                        }
                    })
                    .catch(error => console.error('筛选销售机会失败:', error));
            }
            
            function resetFilters() {
                document.getElementById('searchOpportunity').value = '';
                document.getElementById('filterStatus').value = '';
                document.getElementById('filterPriority').value = '';
                loadOpportunities(); // 重新加载所有销售机会
            }
            
            // 当客户选择改变时更新显示
            document.getElementById('clientId').addEventListener('change', function() {
                const selectedClientId = this.value;
                if (selectedClientId) {
                    const selectedClient = clients.find(client => client.id == selectedClientId);
                    if (selectedClient) {
                        // 可以在这里显示客户的相关信息
                        console.log('已选择客户:', selectedClient.name);
                    }
                }
            });
            
            // 当概率改变时自动更新预期收入
            document.getElementById('probability').addEventListener('input', updateExpectedRevenue);
            document.getElementById('amount').addEventListener('input', updateExpectedRevenue);
            
            function updateExpectedRevenue() {
                const amount = parseFloat(document.getElementById('amount').value) || 0;
                const probability = parseInt(document.getElementById('probability').value) || 0;
                const expectedRevenue = (amount * probability / 100).toFixed(2);
                
                // 如果页面上有显示预期收入的元素，可以更新它
                const expectedRevenueElement = document.getElementById('expectedRevenue');
                if (expectedRevenueElement) {
                    expectedRevenueElement.textContent = expectedRevenue.toLocaleString('zh-CN', {style: 'currency', currency: 'CNY'});
                }
            }
        </script>
    </th:block> 